package com.winit.util;

import com.mysql.fabric.jdbc.FabricMySQLConnection;
import com.mysql.jdbc.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * Created by wangjian on 17/6/19.
 */
public class ConnUtil {

    public static FabricMySQLConnection getConnection(String serverGroup, String shardTable, String shardKey) throws Exception {
        StringBuffer baseUrl = new StringBuffer();
        baseUrl.append("jdbc:mysql:fabric://").append(ConfigUtil.getValue("mysql.fabric.hostname")).append(":")
                .append(Integer.valueOf(ConfigUtil.getValue("mysql.fabric.port"))).append("/")
                .append(ConfigUtil.getValue("mysql.fabric.database"));

        if (StringUtils.isEmptyOrWhitespaceOnly(serverGroup) && StringUtils.isEmptyOrWhitespaceOnly(shardTable)) {
            System.out.println("serverGroup 和 shardTable 不能同时为空!");
            throw new Exception("serverGroup 和 shardTable 不能同时为空!");
        }

        if (!StringUtils.isEmptyOrWhitespaceOnly(serverGroup) && !StringUtils.isEmptyOrWhitespaceOnly(shardTable)) {
            System.out.println("serverGroup 和 shardTable 不能同时存在!");
            throw new Exception("serverGroup 和 shardTable 不能同时存在!");
        }

        if (!StringUtils.isEmptyOrWhitespaceOnly(serverGroup)) {
            baseUrl.append("?fabricServerGroup=").append(serverGroup);
        } else {
            baseUrl.append("?fabricShardTable=").append(shardTable);
        }

        if (!com.mysql.jdbc.Util.isJdbc4()) {
            Class.forName("com.mysql.fabric.jdbc.FabricMySQLDriver");
            System.out.println("load driver");
        }

        FabricMySQLConnection rawConnection = (FabricMySQLConnection) DriverManager.getConnection(baseUrl.toString()
                , ConfigUtil.getValue("mysql.fabric.user"), ConfigUtil.getValue("mysql.fabric.password"));

        if (!StringUtils.isEmptyOrWhitespaceOnly(shardTable) && !StringUtils.isEmptyOrWhitespaceOnly(shardKey)) {
            rawConnection.setShardKey(shardKey);
        }

        return rawConnection;

    }

}
